package org.finesys.common.excel.handler;

import cn.idev.excel.EasyExcel;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.write.metadata.WriteSheet;
import org.finesys.common.excel.annotaion.ResponseExcel;
import org.finesys.common.excel.annotaion.Sheet;
import org.finesys.common.excel.enhance.WriterBuilderEnhancer;
import org.finesys.common.excel.exception.ExcelException;
import org.finesys.common.excel.properties.ExcelConfigProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * sheet 写出处理器
 */
public class ManySheetWriteHandler extends AbstractSheetWriteHandler {


    public ManySheetWriteHandler(ExcelConfigProperties configProperties, ObjectProvider<List<Converter<?>>> converterProvider, WriterBuilderEnhancer excelWriterBuilderEnhance) {
        super(configProperties, converterProvider, excelWriterBuilderEnhance);
    }

    @Override
    public boolean support(Object obj) {
        if (obj instanceof List) {
            List<?> objects = (List<?>) obj;
            return !objects.isEmpty() && objects.get(0) instanceof List;
        } else {
            throw new ExcelException("@ResponseExcel 返回值必须为list类型！");
        }
    }

    @Override
    public void write(Object o, HttpServletResponse response, ResponseExcel responseExcel) {
        List<?> list = (List<?>) o;
        ExcelWriter excelWriter = getExcelWriter(response, responseExcel);
        Sheet[] sheets = responseExcel.sheets();
        WriteSheet writeSheet;
        for (int i = 0; i < sheets.length; i++) {
            Sheet sheet = sheets[i];
            List<?> eleList = (List<?>) list.get(i);
            if (CollectionUtils.isEmpty(eleList)) {
                writeSheet = EasyExcel.writerSheet(sheet.sheetName()).build();
            } else {
                // 有模板则不指定sheet名
                Class<?> dataClass = eleList.get(0).getClass();
                writeSheet = this.sheet(sheet, dataClass, responseExcel.template(), responseExcel.headGenerator());
            }
            //写入数据
            writeData(eleList, excelWriter, writeSheet, responseExcel);
        }
        //写入完成
        excelWriter.finish();
    }
}
